package com.example.woke1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.woke.CheckpaypswActivity;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class DingqibuyActivity extends Activity implements OnClickListener {

	private EditText mEmoney;
	private Intent intent;
	private String money;
	private float mEmoneys;
	private TextView mTok;
	private MyApp application;
	private String user_money;//�в����

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dingqibuy);
		intent = getIntent();
		application = (MyApp) getApplication();
		intview();
		
	}

	private void intview() {
		getmywallet();
		String interest = intent.getStringExtra("interest");
		product_title = intent.getStringExtra("product_title");
		String min_money = intent.getStringExtra("min_money");
//		min_moneys = Integer.parseInt(min_money);
		min_moneys = (int) Float.parseFloat(min_money);
		id = intent.getStringExtra("id");
		mEmoneys = Float.parseFloat(min_money);
		String exp_money = intent.getStringExtra("exp_money");
		String date = intent.getStringExtra("date");
		TextView mTlilv = (TextView) findViewById(R.id.avdingqi_text_zhlilv);
		mTlilv.setText("年化收益： "+interest+"%");
		TextView mTdate = (TextView) findViewById(R.id.avdingqi_text_zhdate);
		mTdate.setText("投资期限： "+date+"天");
		TextView mTqitou = (TextView) findViewById(R.id.avdingqi_text_zhqitou);
		mTqitou.setText("起投金额： "+min_money+"元");
		TextView mTlast= (TextView) findViewById(R.id.avdingqi_text_last);
		mTlast.setText("剩余金额： "+exp_money+"元");
		findViewById(R.id.avdingqi_image_back).setOnClickListener(this);
		mTok = (TextView) findViewById(R.id.avdingqibuy_text_buy);
		mTok.setOnClickListener(this);
		mProgress = findViewById(R.id.avdingqibuy_progress);
		mTsefmoney = (TextView) findViewById(R.id.avdingqi_text_selfmoney);
		TextView mTtitle = (TextView) findViewById(R.id.avdingqi_text_title);
		mTtitle.setText(product_title);
		mEmoney = (EditText) findViewById(R.id.avdingqibuy_edit_money);
		mEmoney.addTextChangedListener(watcher);
		mEmoney.setHint("最低起投金额"+min_money+"元");
	}
	
	private TextWatcher watcher = new TextWatcher() {
	    @Override
	    public void onTextChanged(CharSequence s, int start, int before, int count) {
	    }
	    @Override
	    public void beforeTextChanged(CharSequence s, int start, int count,
	            int after) {
	    }
	    
	    @Override
	    public void afterTextChanged(Editable s) {
	    	String day1 = ""+mEmoney.getText().toString().trim();
	    	if(!day1.equals("")){
	    		float parseInt = Float.parseFloat(day1);
	    		float user_moneys = Float.parseFloat(user_money);
//	    		int parseInt = Integer.parseInt(day1);
	    		if(mEmoneys > parseInt){
	    			mTok.setTextColor(getResources().getColor(R.color.fmuserline));
	    			mTok.setClickable(false);
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
	    		}else{
	    			if(user_moneys < parseInt){
	    				mTok.setTextColor(getResources().getColor(R.color.fmuserline));
		    			mTok.setClickable(false);
	    			}else{
	    				mTok.setTextColor(getResources().getColor(R.color.lightred));
	    				mTok.setClickable(true);
	    			}
	    		}
	    	}else{
//	    		mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
	    	}
	    }
	};
	private TextView mTsefmoney;
	private String product_title;
	private View mProgress;
	private String id;
	private int min_moneys;
	
	private void getmywallet() {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(DingqibuyActivity.this);    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "user");
		params.put("a", "wallet");
		params.put("username", application.getDatas_load().getUser_login());
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("钱包", ""+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						JSONObject jsi = jsonObject.getJSONObject("data");
						user_money = jsi.getString("user_money");
						mTsefmoney.setText("可用剩余"+user_money.subSequence(0, user_money.length() - 3)+"元");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
//			Toast.makeText(getActivity(), "ʧ�ܣ�", Toast.LENGTH_SHORT).show();
				Log.e("response", "失败！"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
//				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
//				mBar.setVisibility(View.GONE);
				Log.e("response", "完成");
			}
		});
	}

		@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == 700 && resultCode == 600){
			payintozhcai();
//			Toast.makeText(ZhcailicaiinActivity.this, "ת���ɹ�", Toast.LENGTH_SHORT).show();
		}
	}
		
		private void payintozhcai() {
			if(application.getDatas_load ()==null)return;
			AsyncHttpClient ahc = new AsyncHttpClient();
	        PersistentCookieStore myCookieStore = new PersistentCookieStore(DingqibuyActivity.this);    
	        ahc.setCookieStore(myCookieStore); 
			RequestParams params = new RequestParams();
			params.put("g", "api");
			params.put("m", "financial");
			params.put("a", "addDingqi");
			params.put("userid", application.getDatas_load().getId());
			params.put("money", money);
			params.put("finanid", id);
			Log.e("params", params.toString());
			ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						JSONObject response) {
					super.onSuccess(statusCode, headers, response);
					Log.e("购买定期", "成功"+response);
					try {
						String flag = response.getString("flag");
						String info = response.getString("info");
						if(flag.equals("success")){
							intent.setClass(DingqibuyActivity.this, ZhcailicaisuecssActivity.class);
							intent.putExtra("money", money);
							intent.putExtra("type", "buy");
							intent.putExtra("product_title", product_title);
							startActivity(intent);
						}else{
							Toast.makeText(DingqibuyActivity.this, "买入失败，"+info, Toast.LENGTH_SHORT).show();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int statusCode, Header[] headers,
						String responseString, Throwable throwable) {
					super.onFailure(statusCode, headers, responseString, throwable);
					Toast.makeText(DingqibuyActivity.this, "服务器未响应", Toast.LENGTH_SHORT).show();
//					Log.e("�ϴ�", "�ֻ��ʧ��"+responseString);
				}
				
				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
					mProgress.setVisibility(View.VISIBLE);
				}
				
				@Override
				public void onFinish() {
					super.onFinish();
					mProgress.setVisibility(View.GONE);
				}
			});
		}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avdingqi_image_back:
			finish();
			break;
			
		case R.id.avdingqibuy_text_buy:
			money = ""+ mEmoney.getText().toString().trim();
			if(money.equals("")){
				Toast.makeText(DingqibuyActivity.this, "请输入金额", Toast.LENGTH_SHORT).show();
			}else{
				int parseInt = Integer.parseInt(money);
//				float parseInt = Float.parseFloat(money);
				if(parseInt < min_moneys){
					Toast.makeText(DingqibuyActivity.this, "起投金额需大于"+min_moneys+"元,且为"+min_moneys+"的倍数", Toast.LENGTH_SHORT).show();
				}else if(parseInt % min_moneys > 0){
					Toast.makeText(DingqibuyActivity.this, "起投金额需大于"+min_moneys+"元,且为"+min_moneys+"的倍数", Toast.LENGTH_SHORT).show();
				}else{
					intent.setClass(DingqibuyActivity.this, CheckpaypswActivity.class);
					intent.putExtra("paymoney", money);
					startActivityForResult(intent, 700);
				}
			}
			break;

		default:
			break;
		}
	}
}
